import React, { Component } from "react";
import { connect } from "react-redux";
import { createForm } from "rc-form";
import yhTools from "@tools/yh";
import MainLayout from "@component/mainLayout/mainLayout";
import { InterfaceG } from "@config/Config";
import Button from "@component/button/index";
import { InputItem, List, Picker, Toast } from "antd-mobile";
import { checkTool } from "plugin-tool-check";
import BackModal from "@component/backModal/index";
import AgreeCheckbox from "@component/agreeCheckbox/index";
import "./UploadIDCardImg.scss";

/**小辉宝二类户开户 */
class UploadIDCardImg extends Component {
	constructor(props) {
		super(props);
		this.state = {
			loadStatus: "1", // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
			imageFront: require("../../../images/idcard/card_front.png"),
			imageBack: require("../../../images/idcard/card_back.png"),
			imageAdd: require("../../../images/idcard/icon-card_add.png"),
			chooseImageFront: "-1", //选择人像面图片地址
			chooseImageBack: "-1", //选择国徽面图片地址

			agreeFlag: false,
			isVisible: false, //挽留对话框是否显示

			username: "", //姓名
			sex: "",
			nation: "",
			birth: "",
			address: "", //地址
			organs: "", //签发机关
			signStartDate: "", //签发日期
			validDate: "", //有效期
			frontImageUrl: "",
			backImageUrl: "",
			idno: "", //身份证号码

			bindCardNo: "", //选择的银行卡唯一标识
			professionCode: "", //职业
			invitationCode: "", //推荐码
			profession: [
				{
					label: "国家机关及企事业单位负责人",
					value: "10000"
				},
				{
					label: "专业技术人员",
					value: "20000"
				},
				{
					label: "法律、社会和宗教专业人员",
					value: "20700"
				},
				{
					label: "教学人员",
					value: "20800"
				},
				{
					label: "办事人员和有关人员",
					value: "30000"
				},
				{
					label: "社会生产服务和生活服务人员",
					value: "40000"
				},
				{
					label: "批发与零售服务人员",
					value: "40100"
				},
				{
					label: "住宿和餐饮服务人员",
					value: "40300"
				},
				{
					label: "金融服务人员",
					value: "40500"
				},
				{
					label: "租赁和商务服务人员",
					value: "40700"
				},
				{
					label: "文化/体育/娱乐服务人员",
					value: "41300"
				},
				{
					label: "农、林、牧、渔业生产及辅助人员",
					value: "50000"
				},
				{
					label: "生产制造及有关人员",
					value: "60000"
				},
				{
					label: "废弃资源综合利用人员",
					value: "62700"
				},
				{
					label: "军人",
					value: "70000"
				},
				{
					label: "其他从业人员",
					value: "80000"
				}
			],

			spaceID: "" // 随记生成一个计数
		};
	}

	//初始化数据
	componentDidMount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom,
			agreeFlag: !!yhTools.isXiaoHuiBao()
		});
	}
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}

		this.setState({
			isVisible: false
		});
	}
	/**
	 * 键盘事件
	 */
	keyboardEvent = () => {
		// let winHeight = document.documentElement.clientHeight;
		// document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
		//     winHeight * obj.heightper + "px";
	};
	//选择图片
	chooseImage(index) {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName:
				this.props.getAppPlatformsDatas.mobile + "_card_" + index + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				switch (index) {
					case 0:
						//上传身份证人像图片
						this.updateImage(2, resp.data.path);
						this.setState({
							imageFront: resp.data.base64
						});
						break;
					case 1:
						//上传身份证国徽图片
						this.updateImage(4, resp.data.path);
						this.setState({
							imageBack: resp.data.base64
						});
						break;
					default:
						break;
				}
			},
			() => {}
		);
	}

	//上传身份证照片
	updateImage(index, path) {
		let imageData;
		let _that = this;
		if (index == 2) {
			imageData = {
				name: "CardImg.jpeg",
				path: path,
				params: {
					fileType: 2, //2正面，4反面，5头像
					channelCode: "YHB", //渠道编号,
					version: "1.0",
					lnid: this.props.getAppPlatformsDatas.lnid
				}
			};
		} else {
			imageData = {
				name: "CardBackImg.jpeg",
				path: path,
				params: {
					fileType: 4, //2正面，4反面，5头像
					channelCode: "YHB", //渠道编号,
					version: "1.0",
					lnid: this.props.getAppPlatformsDatas.lnid
				}
			};
		}
		let jsonDataArr = [imageData];
		let objs = {
			url: yhTools.isXiaoHuiBao()
				? InterfaceG.xhbUploadIdCardOcrForHt
				: InterfaceG.uploadIdCardOcrForHt,
			imageArray: jsonDataArr
		};
		Toast.loading("加载中...", 100, () => {});
		yhTools.request(objs).then(resp => {
			Toast.hide();
			if (resp.code == "0") {
				Toast.info("上传成功", 2);
				if (index == "2") {
					_that.setState({
						chooseImageFront: "1", //选择人像面图片上传成功
						username: resp.data.username, //姓名
						idno: resp.data.idno, //身份证号
						sex: resp.data.sex, //性别
						address: resp.data.address, //地址
						nation: resp.data.nation, //民族
						birth: resp.data.birth, //出生日期
						frontImageUrl: resp.data.frontImageUrl,
						frontImage: resp.data.frontImage
					});
				} else {
					_that.setState({
						chooseImageBack: "1", //选择国徽面图片上传成功
						organs: resp.data.organs, //签发机关
						signStartDate: resp.data.signStartDate, //签发日期
						validDate: resp.data.validDate, //有效期
						backImageUrl: resp.data.backImageUrl,
						backImage: resp.data.backImage
					});
				}
			} else {
				if (index == "2") {
					_that.setState({
						chooseImageFront: "-1", //选择人像面图片上传失败
						idno: "", //身份证号
						sex: "", //性别
						address: "", //地址
						nation: "", //民族
						birth: "" //出生日期
					});
				} else {
					_that.setState({
						chooseImageBack: "-1", //选择国徽面图片上传失败
						organs: "", //签发机关
						signStartDate: "", //签发日期
						validDate: "" //有效期
					});
				}
				Toast.info(resp.message, 2);
			}
		});
	}

	//提交数据
	commitImage() {
		// if (!this.state.allInputFlag) {
		//     return;
		// }
		const {
			username,
			idno,
			sex,
			address,
			nation,
			birth,
			organs,
			signStartDate,
			validDate,
			agreeFlag,
			professionValue,
			professionCode,
			frontImage,
			frontImageUrl,
			backImage,
			backImageUrl
		} = this.state;
		if (!username) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		//校验名字
		let patt1 = /[^\u4e00-\u9fa5]/g; //匹配非汉字字符
		if (patt1.test(username)) {
			Toast.info("姓名只能为汉字", 2);
			return false;
		}
		if (!idno) {
			Toast.info("请输入身份证号", 2);
			return false;
		}
		//校验身份证
		let patt2 = {
			valueParams: idno.replace(/\s*/g, "")
		};
		if (!checkTool.isIDNo(patt2)) {
			Toast.info("请输入正确的身份证号", 2);
			return false;
		}
		if (!address) {
			Toast.info("请输入身份证地址", 2);
			return false;
		} else if (
			!checkTool.isAddress({
				valueParams: address,
				validateRules: /[\u4e00-\u9fa5]{1,50}/
			})
		) {
			Toast.info("请输入正确身份证地址", 2);
			return false;
		}
		if (this.props.getAppPlatformsDatas.lnid != "802") {
			if (professionCode == "") {
				Toast.info("请选择你的职业", 2);
				return false;
			}
		}
		if (!agreeFlag) {
			Toast.info("请先勾选协议", 2);
			return false;
		}
		let dataJSON = {
			url: InterfaceG.xhbConformIdCardInfo,
			params: {
				channelCode: "YHB", //渠道编号,
				applyNo: this.props.getAppPlatformsDatas.applyNo, //申请流水号
				lnid: this.props.getAppPlatformsDatas.lnid, //产品id
				userName: username, //姓名
				idNo: idno, //身份证号
				sex: sex, //性别
				address: address, //地址
				nation: nation, //民族
				birth: birth, //出生日期
				organs: organs, //签发机关
				cardStartTime: signStartDate, //签发日期
				cardEndTime: validDate, //有效期
				professionValue: professionValue, //职业
				professionCode: professionCode,
				frontImage: frontImage, //人脸照片
				backImage: backImage, //国徽照片
				frontImageUrl: frontImageUrl,
				backImageUrl: backImageUrl,
				version: "1.0"
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100, () => {});
		yhTools.request(dataJSON).then(resp => {
			Toast.hide();
			if (resp.code == "0") {
				// 跳转短信验证页面参数
				this.props.history.push({
					pathname: `/liveness/${JSON.stringify({
						userName: dataJSON.params.userName,
						idNo: dataJSON.params.idNo
					})}`,
					query: {
						form: "xhbFace"
					}
				});
			} else {
				Toast.info(resp.message, 2);
			}
		});
	}
	showModal = () => {
		this.setState({
			isVisible: true
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isVisible: false
		});
		!booleanValue && this.props.history.goBack();
	};
	render() {
		const { getFieldProps } = this.props.form;
		const headerParams = {
			header: {
				title: "身份影像"
			},
			isModal: true,
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const {
			isVisible,
			chooseImageFront,
			imageFront,
			imageBack,
			imageAdd,
			chooseImageBack,
			username,
			idno,
			address,
			signStartDate,
			validDate
		} = this.state;
		return (
			<MainLayout pageParams={headerParams} handleBack={this.showModal}>
				<BackModal
					product={this.props.getAppPlatformsDatas.lnid}
					isVisible={isVisible}
					onClick={this.onModalClick}
				/>
				<div className="update_image_page">
					<div className="content">
						{/*<div className="content-tip">请拍摄并上传身份证</div>*/}

						<div className="div-flex">
							<div
								className="update-image"
								onClick={this.chooseImage.bind(this, 0)}
							>
								<img className="idcard-img" src={imageFront} alt="" />
								<img
									className="img-add"
									src={
										chooseImageFront === "1"
											? require("../../../images/idcard/icon-card_add_ed.png")
											: imageAdd
									}
									alt=""
								/>
								<div className="tip_idcard-common"> 上传人像面</div>
							</div>
							<div
								className="update-image"
								onClick={this.chooseImage.bind(this, 1)}
							>
								<img className="idcard-img" src={imageBack} alt="" />
								<img
									className="img-add"
									src={
										chooseImageBack === "1"
											? require("../../../images/idcard/icon-card_add_ed.png")
											: imageAdd
									}
									alt=""
								/>

								<div className="tip_idcard-common"> 上传国徽面</div>
							</div>
						</div>
					</div>
					{(chooseImageFront != "1" || chooseImageBack != "1") && (
						<div className="line-1">
							<div className="image-require">
								<div className="line-div" />
								<div className="line-div image_require-tip">身份证拍摄示例</div>
								<div className="line-div" />
							</div>
							<div className="image-tip">
								<div className="image-tip-item image-item-one" />
								<div className="image-tip-item image-item-two" />
								<div className="image-tip-item image-item-three" />
								<div className="image-tip-item item-last image-item-four" />
							</div>

							<div className="bottom-tips-far">
								<img
									className="tips-img"
									src={require("../../../images/idcard/icon-tips.png")}
									alt=""
								/>
								<div className="r-text">
									<span className="t-blue">请同时上传身份证正反面，</span>
									并仔细核对您的证件信息，如果有误请重新上传
								</div>
							</div>
						</div>
					)}
					{chooseImageFront === "1" && chooseImageBack === "1" && (
						<div>
							<div className="line-2">
								<List className="list-own">
									<InputItem
										onChange={this.InputOnChange.bind(this, "username")}
										maxLength={30}
										placeholder="请输入姓名"
										value={username}
										clear={true}
									>
										姓名
									</InputItem>
									<InputItem
										onChange={this.InputOnChange.bind(this, "idno")}
										maxLength={18}
										placeholder="请输入身份证号"
										value={idno}
										clear={true}
									>
										身份证号
									</InputItem>
									<InputItem
										onChange={this.InputOnChange.bind(this, "address")}
										maxLength={50}
										placeholder="请输入身份证地址"
										value={address}
										clear={true}
									>
										身份证住址
									</InputItem>
								</List>
								<List className="list-own">
									<InputItem editable={false} value={signStartDate}>
										证件起始时间
									</InputItem>
									<InputItem editable={false} value={validDate}>
										证件截止时间
									</InputItem>
								</List>
							</div>
							<div
								className="other_info"
								style={{
									display:
										this.props.getAppPlatformsDatas.lnid == "802"
											? "none"
											: "block"
								}}
							>
								<Picker
									extra="请选择您的职业"
									data={this.state.profession}
									title="请选择"
									{...getFieldProps("professionValue", {
										initialValue: [this.state.professionCode]
									})}
									cols={1}
									onChange={this.pickerSelected.bind(this)}
									// onOk={this.pickerSelected.bind(this)}
									onDismiss={e => console.log("dismiss", e)}
								>
									<List.Item arrow="horizontal">职业</List.Item>
								</Picker>
							</div>
							{!yhTools.isXiaoHuiBao() && (
								<div className="agree-wrapper">
									<AgreeCheckbox
										checked={this.state.agreeFlag}
										onChange={() => this.checkBoxClick()}
									>
										<span className="multi-line">
											阅读并同意签署
											<a
												className="blue-color"
												onClick={e => this.openContract(e, 2)}
											>
												《个人征信授权书》
											</a>
										</span>
									</AgreeCheckbox>
								</div>
							)}
							<Button
								style={{ marginTop: "0.78rem" }}
								onClick={this.commitImage.bind(this)}
								disabled={!this.state.agreeFlag}
								buttonStyle={{
									height: "1rem",
									lineHeight: "1rem"
								}}
							>
								确认身份信息并继续
							</Button>
						</div>
					)}

					<div id={"keybordb_" + this.state.spaceID}></div>
				</div>
			</MainLayout>
		);
	}

	pickerSelected(value) {
		let arr = this.state.profession;
		let title = "";
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].value === value[0]) {
				title = arr[i].label;
				break;
			}
		}
		this.setState(
			{
				professionValue: title,
				professionCode: value[0]
			},
			() => {
				this.checkAllInputText();
			}
		);
	}

	InputOnChange(v, value) {
		const regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
		value = value.replace(regStr, "");
		this.setState(
			{
				[v]: value.trim()
			},
			() => {
				this.checkAllInputText();
			}
		);
	}

	//勾选协议
	checkBoxClick() {
		this.setState(
			{
				agreeFlag: !this.state.agreeFlag
			},
			() => {
				this.checkAllInputText();
			}
		);
	}

	checkAllInputText() {
		// console.log(this.state.chooseImageFront, this.state.chooseImageBack, this.state.username, this.state.idno, this.state.address, this.state.professionCode)
		if (this.state.agreeFlag) {
			if (
				this.state.chooseImageFront === "1" &&
				this.state.chooseImageBack === "1" &&
				this.state.username &&
				this.state.idno &&
				this.state.address &&
				// this.state.signStartDate &&
				// this.state.validDate&&
				this.state.professionCode
			) {
				this.setState({
					allInputFlag: true
				});
			} else {
				this.setState({
					allInputFlag: false
				});
			}
		} else {
			this.setState({
				allInputFlag: false
			});
		}
	}

	//查看协议
	openContract(e, v) {
		e.stopPropagation();
		let pathname = "";
		if (v === 1) {
			pathname = `/personalInformationLicense`;
		} else if (v === 2) {
			pathname = `/personalCreditAuthorization`;
		}
		this.props.history.push({
			pathname: pathname,
			params: {}
		});
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps() {
	return {};
}

const UploadIDCardImgPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(UploadIDCardImg);
export default createForm()(UploadIDCardImgPage);
